<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <title>Reviewing碳减排记录审查</title>
  <link rel="icon" href="/img/team.jpg" type="image/JPG">
  <!-- 引入Bootstrap和jQuery的CDN链接 -->
  <link rel="stylesheet" href="./css/bootstrap.min.css">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css">
  <link rel="stylesheet" href="./css/ios-design.css">
  <script src="./js/jquery.min.js"></script>
  <script src="./js/bootstrap.min.js"></script>
  <script src="./js/utils.js"></script>
  <script src="./js/nav.js"></script>
  <!-- 省略其他链接和样式 -->
  <style>
    /* Basic body styles using CSS Variables */
    body {
      background-color: var(--background-color-light);
      color: var(--text-color-light);
      font-family: "Microsoft YaHei", sans-serif;
      transition: background-color 0.3s ease, color 0.3s ease;
    }

    body.dark-theme {
      background-color: var(--background-color-dark);
      color: var(--text-color-dark);
    }

    .card {
      transition: transform 0.3s ease, box-shadow 0.3s ease, background-color 0.3s ease; /* 添加过渡动画 */
      cursor: pointer;
      background-color: var(--card-bg-light); /* Use CSS variable */
      border: 1px solid var(--border-color-light); /* Add border */
      border-radius: 12px; /* Consistent border radius */
    }

    body.dark-theme .card {
        background-color: var(--card-bg-dark);
        border: 1px solid var(--border-color-dark);
    }


    .card:hover {
      transform: translateY(-5px); /* 鼠标悬停时上移 */
      box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15); /* 鼠标悬停时增加阴影 */
    }
    body.dark-theme .card:hover {
        box-shadow: 0 6px 12px rgba(255, 255, 255, 0.1); /* Adjusted shadow for dark mode */
    }


    .card-img-top {
      height: 200px;
      object-fit: cover;
      border-top-left-radius: 11px; /* Adjust for border */
      border-top-right-radius: 11px; /* Adjust for border */
    }

    .card-body {
      padding: 15px;
      /* background-color: #ffffff; /* Removed hardcoded background */
      border-bottom-left-radius: 11px; /* Adjust for border */
      border-bottom-right-radius: 11px; /* Adjust for border */
    }

    .card-title {
      font-size: 18px;
      font-weight: bold;
      color: var(--text-color-light); /* Use CSS variable */
      margin-bottom: 10px;
    }
     body.dark-theme .card-title {
        color: var(--text-color-dark);
     }

    .card-text {
      font-size: 14px;
      color: var(--secondary-text-color-light); /* Use CSS variable */
      height: 60px; /* Keep height limit */
      overflow: hidden; /* Keep overflow */
      text-overflow: ellipsis; /* Keep ellipsis */
    }
    body.dark-theme .card-text {
        color: var(--secondary-text-color-dark);
    }


    .card-text-row {
      padding: 0.5rem;
      margin: 0;
      background-color: var(--table-row-bg-light); /* Use CSS variable */
      border-bottom: 1px solid var(--border-color-light); /* Use CSS variable */
    }
     body.dark-theme .card-text-row {
         background-color: var(--table-row-bg-dark);
         border-bottom: 1px solid var(--border-color-dark);
     }

    .card-text-row:last-child {
      border-bottom: 0;
    }

    .auth-status {
      display: inline-block;
      padding: 0.25em 0.5em;
      border-radius: 5px;
      color: white; /* Keep white for contrast on colored backgrounds */
      font-weight: bold;
      text-align: center;
      width: 100%;
      margin-top: 10px;
    }

    .auth-yes {
      background-color: #28a745;
      /* color: black; */ /* Let default contrast work */
    }

    .auth-no {
      background-color: #dc3545;
       /* color: black; */ /* Let default contrast work */
    }

    .auth-non {
      background-color: #ffc107;
      color: black; /* Keep black for yellow */
    }


    /* Use CSS variables for navbar, adjusting as needed */
    .navbar {
      /* background-color: #007bff; */ /* Replaced by ios-design.css */
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    }
    /* body.dark-theme .navbar { */
      /* Define dark theme navbar background if needed, or let ios-design handle it */
    /* } */

    /* Bootstrap overrides if necessary for dark mode */
    body.dark-theme .form-control {
        background-color: var(--input-bg-dark);
        color: var(--text-color-dark);
        border-color: var(--border-color-dark);
    }
    body.dark-theme .form-control::placeholder {
        color: var(--secondary-text-color-dark);
    }
    body.dark-theme .input-group-text {
        background-color: var(--input-group-bg-dark);
        border-color: var(--border-color-dark);
        color: var(--text-color-dark);
    }

    body.dark-theme .btn-primary {
        background-color: var(--primary-color); /* Use primary color variable */
        border-color: var(--primary-color);
        color: white; /* Assuming primary color contrasts well with white */
    }
    /* Add hover/active states if needed */

     body.dark-theme .btn-secondary {
        background-color: var(--secondary-button-bg-dark);
        border-color: var(--secondary-button-border-dark);
        color: var(--secondary-button-text-dark);
    }
     body.dark-theme .btn-secondary:hover {
        background-color: var(--secondary-button-hover-bg-dark);
        border-color: var(--secondary-button-hover-border-dark);
    }

    /* Theme Toggle Button Styles */
    #theme-toggle-button {
      position: fixed;
      bottom: 20px;
      right: 20px;
      background-color: var(--button-bg-light);
      color: var(--button-text-light);
      border: 1px solid var(--border-color-light);
      border-radius: 50%;
      width: 45px;
      height: 45px;
      font-size: 20px;
      display: flex;
      align-items: center;
      justify-content: center;
      cursor: pointer;
      z-index: 1050; /* Ensure it's above other elements */
      transition: background-color 0.3s ease, color 0.3s ease, border-color 0.3s ease;
      box-shadow: 0 2px 5px rgba(0,0,0,0.2);
    }

    body.dark-theme #theme-toggle-button {
      background-color: var(--button-bg-dark);
      color: var(--button-text-dark);
      border: 1px solid var(--border-color-dark);
       box-shadow: 0 2px 5px rgba(255,255,255,0.15);
    }

     #theme-toggle-button:hover {
        opacity: 0.8;
     }

    /* 省略其余样式 */
    @keyframes spin {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }
  </style>
</head>
<body>
<div id="loading">
  <div class="loader"></div>
</div>

<!-- Theme Toggle Button -->
<button id="theme-toggle-button" aria-label="Toggle theme">
  <i class="fas fa-sun"></i> <!-- Default icon -->
</button>

<!-- 导航栏容器，将由JavaScript加载 -->
<div id="navbar-container"></div>

<div class="container">
  <h3>碳减排记录审查</h3><br>

  <!-- Search Bar -->
  <div class="row mb-3">
    <div class="col-md-6">
      <div class="input-group">
        <input type="text" id="searchInput" class="form-control" placeholder="Search by User ID or Email...">
        <div class="input-group-append">
          <button class="btn btn-primary" type="button" id="searchButton">Search</button>
          <button class="btn btn-secondary" type="button" id="clearSearchButton">Clear</button>
        </div>
      </div>
    </div>
  </div>

  <div id="records" class="row">
    <!-- 交易记录将在这里动态生成 -->
  </div>
  <!-- Pagination Controls -->
  <div id="pagination-controls" class="mt-4 text-center"></div>
</div>

<script>
  // Theme toggling logic
  const themeToggleButton = document.getElementById('theme-toggle-button');
  const currentTheme = localStorage.getItem('theme') || 'auto'; // Default to 'auto'

  function applyTheme(theme) {
    const body = document.body;
    const icon = themeToggleButton.querySelector('i');
    body.classList.remove('light-theme', 'dark-theme'); // Remove existing theme classes

    if (theme === 'dark' || (theme === 'auto' && window.matchMedia('(prefers-color-scheme: dark)').matches)) {
      body.classList.add('dark-theme');
      icon.className = 'fas fa-moon'; // Moon icon for dark
      localStorage.setItem('theme', theme);
        // Update Bootstrap components for dark mode if necessary
        document.querySelectorAll('.modal-content').forEach(el => el.classList.add('bg-dark', 'text-light')); // Example for modals
        document.querySelectorAll('.table').forEach(el => el.classList.add('table-dark')); // Example for tables


    } else {
      body.classList.add('light-theme'); // Explicitly add light-theme or rely on default
      icon.className = 'fas fa-sun'; // Sun icon for light
      localStorage.setItem('theme', theme);
       // Revert Bootstrap components if they were changed for dark mode
       document.querySelectorAll('.modal-content').forEach(el => el.classList.remove('bg-dark', 'text-light'));
       document.querySelectorAll('.table').forEach(el => el.classList.remove('table-dark'));
    }
     // Update icon for auto based on effective theme
    if (theme === 'auto') {
        icon.className = window.matchMedia('(prefers-color-scheme: dark)').matches ? 'fas fa-adjust' : 'fas fa-adjust'; // Use adjust icon for auto
         // Adjust icon based on actual applied theme in auto mode
        //icon.className = document.body.classList.contains('dark-theme') ? 'fas fa-moon' : 'fas fa-sun'; // Or show moon/sun based on result
        icon.className = 'fas fa-adjust'; // Keep 'auto' icon simple
    }

  }

  function cycleTheme() {
    const themes = ['light', 'dark', 'auto'];
    let currentThemeIndex = themes.indexOf(localStorage.getItem('theme') || 'auto');
    let nextThemeIndex = (currentThemeIndex + 1) % themes.length;
    applyTheme(themes[nextThemeIndex]);
  }

  // Apply initial theme on load
  applyTheme(currentTheme);

  // Listen for system theme changes if in 'auto' mode
  window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => {
    if (localStorage.getItem('theme') === 'auto') {
      applyTheme('auto');
    }
  });

  // Add event listener to the button
  themeToggleButton.addEventListener('click', cycleTheme);

  $(document).ready(function () {
    verifyAdmin()
    // Search button click
    $('#searchButton').on('click', function() {
      currentSearchTerm = $('#searchInput').val();
      fetchTransactionsForAdmin(1, currentSearchTerm); // Reset to page 1 on new search
    });

    // Clear search button click
    $('#clearSearchButton').on('click', function() {
      $('#searchInput').val('');
      currentSearchTerm = null;
      fetchTransactionsForAdmin(1, currentSearchTerm); // Reset to page 1 and clear search
    });

    // Optional: Trigger search on Enter key press in search input
    $('#searchInput').on('keypress', function(e) {
      if (e.which == 13) { // Enter key pressed
        $('#searchButton').click(); // Trigger search button click
      }
    });
  })

  var token = localStorage.getItem('token')
  var currentPage = 1;
  var recordsPerPage = 10; // Should match backend default if not specified
  var totalRecords = 0;
  var currentSearchTerm = null; // Variable to hold the current search term

  if (!token) {
    showAlert('请先登录。', 'warning', function() {
      window.location.href = 'index.html'
    })
  }

  function verifyAdmin() {
    var token = localStorage.getItem('token')
    $.ajax({
      type: 'POST',
      data: { token: token },
      url: 'verify_admin.php', // 替换为您的PHP脚本路径
      dataType: 'json',
      success: function (response) {
        if (response.success && response.isAdmin) {
          fetchTransactionsForAdmin(currentPage, currentSearchTerm)
        } else {
          showAlert('非法访问，您没有管理员权限。', 'error', function() {
            window.location.href = 'index.html'
          })
        }
      },
      error: function () {
        showAlert('验证失败，请重试。', 'error', function() {
          window.location.href = 'index.html'
        })
      },
    })
  }

  function fetchTransactionsForAdmin(page, searchTerm) {
    currentPage = page; // Update current page
    currentSearchTerm = searchTerm; // Update current search term
    var token = localStorage.getItem('token')
    
    var requestData = { 
      token: token,
      page: currentPage,
      limit: recordsPerPage
    }; 

    // Add searchTerm to request data if it's not null or empty
    if (currentSearchTerm && currentSearchTerm.trim() !== '') {
      requestData.searchTerm = currentSearchTerm;
    } else {
       // Ensure search term is null if empty for clarity and potentially backend logic
      currentSearchTerm = null; 
    }

    $.ajax({
      type: 'POST',
      data: requestData,
      url: 'gapthis.php', 
      dataType: 'json',
      success: function (response) {
        if (response.success) {
          const recordsContainer = $('#records')
          recordsContainer.empty() // Clear existing records
          
          totalRecords = response.total; 
          currentPage = response.page; 
          recordsPerPage = response.limit;
          // Update search input visually if cleared or term comes back from server
          $('#searchInput').val(response.searchTerm || ''); 

          const records = response.data;
          
          if (records.length === 0) {
             let message = totalRecords === 0 ? '暂无要审批的数据。' : '没有找到匹配的记录。';
             if (currentSearchTerm) {
                 message = `没有找到与 "${currentSearchTerm}" 匹配的待审批记录。`;
             }
             recordsContainer.append(`<p>${message}</p>`);
          } else {
            records.forEach(record => {
              const card = createCard(record)
              recordsContainer.append(card)
            })
          }
          renderPaginationControls(); // Render pagination controls regardless of results
        } else {
          showAlert('错误: ' + response.message, 'error')
          $('#pagination-controls').empty(); 
        }
      },
      error: function () {
        showAlert('请求失败，请重试。', 'error')
        $('#pagination-controls').empty(); 
      },
    })
  }

 function renderPaginationControls() {
    const paginationContainer = $('#pagination-controls');
    paginationContainer.empty();
    
    if (totalRecords === 0) return; // No controls if no records

    const totalPages = Math.ceil(totalRecords / recordsPerPage);

    if (totalPages <= 1) return; // No controls if only one page

    let paginationHTML = '<nav aria-label="Page navigation"><ul class="pagination justify-content-center">';

    // Previous button
    paginationHTML += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                         <a class="page-link" href="#" onclick="fetchTransactionsForAdmin(${currentPage - 1}, currentSearchTerm)">Previous</a>
                       </li>`;

    // Page numbers (simplified version: just show current page / total pages)
    // You could expand this to show more page numbers if needed
    paginationHTML += `<li class="page-item disabled"><span class="page-link">Page ${currentPage} of ${totalPages}</span></li>`; 

    // Next button
    paginationHTML += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                         <a class="page-link" href="#" onclick="fetchTransactionsForAdmin(${currentPage + 1}, currentSearchTerm)">Next</a>
                       </li>`;

    paginationHTML += '</ul></nav>';
    paginationContainer.html(paginationHTML);
 }


  function createCard(record) {
    const authClass = getAuthClass(record.auth)
    const authStatus = getAuthStatus(record.auth)
    // 检查记录的type字段，确定是普通记录还是特殊记录
    const cardTypeClass = record.type === 'spec' ? 'special-card' : ''
    
    // 处理笔记信息（如果为空则显示"无"）
    const notes = record.notes ? record.notes : '无'
    
    // 处理活动日期（如果为空则显示记录创建时间）
    const activityDate = record.activity_date ? record.activity_date : record.time.split(' ')[0]

    return `
        <div class="col-md-4 ${cardTypeClass}">
            <div class="card mb-4">
                <img class="card-img-top" src="${record.img}" alt="User Image">
                <div class="card-body">
                    <h5 class="card-title"></h5>
                    <div class="card-text-row">ID: ${record.id}</div>
                    <div class="card-text-row">UserID: ${record.uid}</div>
                    <div class="card-text-row">Email: ${record.email}</div>
                    <div class="card-text-row">Time: ${record.time}</div>
                    <div class="card-text-row">Activity Date: ${activityDate}</div>
                    <div class="card-text-row">Points: ${record.points}</div>
                    <div class="card-text-row">Raw: ${record.raw}</div>
                    <div class="card-text-row">Activity: ${record.act}</div>
                    <div class="card-text-row">Notes: ${notes}</div>
                    <div class="${authClass}">${authStatus}</div>
                    <button onclick="approveTransaction(${record.id}, '${record.type}','${record.uid}')" class="btn btn-success mx-2">通过</button>
                    <button onclick="rejectTransaction(${record.id}, '${record.type}')" class="btn btn-danger mx-2">打回</button>
                </div>
            </div>
        </div>
    `
  }


  function approveTransaction(id, type, uid) {
    $.ajax({
      type: 'POST',
      url: 'approve_transaction.php', 
      data: { token: localStorage.getItem('token'), transactionId: id, uid: uid, status: 'approved', type: type },
      dataType: 'json',
      success: function (response) {
        if (response.success) {
          showAlert('交易已通过。', 'success')
          // Refresh the current page & search state after approval
          fetchTransactionsForAdmin(currentPage, currentSearchTerm);
        } else {
          showAlert('审批失败: ' + response.message, 'error')
        }
      },
      error: function () {
        showAlert('请求失败，请重试。', 'error')
      },
    })
  }

  function rejectTransaction(id, type) {
    $.ajax({
      type: 'POST',
      url: 'reject_transaction.php', 
      data: { token: localStorage.getItem('token'), transactionId: id, status: 'rejected', type: type },
      dataType: 'json',
      success: function (response) {
        if (response.success) {
          showAlert('交易已打回。', 'success')
          // Refresh the current page & search state after rejection
          fetchTransactionsForAdmin(currentPage, currentSearchTerm);
        } else {
          showAlert('打回失败: ' + response.message, 'error')
        }
      },
      error: function () {
        showAlert('请求失败，请重试。', 'error')
      },
    })
  }

  function getAuthClass(auth) {
    switch (auth) {
      case 'yes':
        return 'auth-yes'
      case 'no':
        return 'auth-no'
      default:
        return 'auth-non'
    }
  }

  function getAuthStatus(auth) {
    switch (auth) {
      case 'yes':
        return '已通过'
      case 'no':
        return '已打回'
      default:
        return '审批中'
    }
  }

  function logout() {
    localStorage.removeItem('token')
    localStorage.removeItem('id')
    localStorage.removeItem('email')
    localStorage.removeItem('username')
    window.location.href = 'index.html'
  }
</script>
<div id="footer-placeholder"></div>
<!-- 省略页脚 -->
</body>
</html>
